package com.sinsz.pay.factory.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.sinsz.common.exception.ApiException;
import com.sinsz.pay.factory.support.SSLConstant;
import com.sinsz.pay.properties.PayProperties;
import com.sinsz.pay.support.AliPayConstant;
import com.sinsz.pay.support.Constant;
import com.sinsz.pay.util.PayUtils;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;

import javax.servlet.http.HttpServletRequest;

/**
 * 支付宝支付实现
 * @author chenjianbo
 */
public class AlipayAppImpl extends BaseAlipayImpl {


    public AlipayAppImpl(PayProperties prop, HttpServletRequest request) {
        super(prop, request);
    }

    @Override
    public String unifiedOrder(String outTradeNo, String body, String detail, int fee, String openid) {
        outTradeNo = formatOutTradeNo(outTradeNo);
        String subject = formatBody(body);
        String desc = formatDetail(subject, detail);
        fee = formatFee(fee);
        String money = formatMoney(fee);
        //请求参数
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setTimeoutExpress(AliPayConstant.ALI_ORDER_EXPIRATION_INTERVAL);
        model.setTotalAmount(money);
        model.setProductCode(AliPayConstant.PRODUCT_CODE);
        model.setBody(desc);
        model.setSubject(subject);
        model.setOutTradeNo(outTradeNo);
        //请求对象
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setBizModel(model);
        request.setNotifyUrl(PayUtils.redirect(super.getProp().getHttp(), super.getProp().getAlipay().getPayNotify(), false));
        //执行请求
        try {
            /**
             * 使用sdkExecute生成支付串，其他接口调用请使用execute执行请求
             */
            AlipayTradeAppPayResponse response = SSLConstant.instance().alipayClient().sdkExecute(request);
            if (response.isSuccess()) {
                return response.getBody();
            } else {
                throw new ApiException(Constant.DEFAULT_EXCEPTION_CODE,Json.toJson(response, JsonFormat.tidy()));
            }
        } catch (AlipayApiException e) {
            e.printStackTrace(System.out);
            throw new ApiException(Constant.DEFAULT_EXCEPTION_CODE,"预支付创建未知异常.");
        }
    }


}
